

# This script produces all Tables and Figures in the Online Appendix
# Tables are produced in a way that they can be directly copied/pasted in a LaTex document

# It needs the following files:  data_main.csv  | data_old.csv


##### Packages (Always RUN before proceeding to Tables and Plots) ########################################################################## 

  #install libraries
  install.packages("data.table") 
  install.packages("dplyr") 
  install.packages("rdrobust") 
  install.packages("lmtest") 
  install.packages("ggplot2") 
  install.packages("AER") 
  install.packages("gridExtra")
  install.packages("sandwich")
  install.packages("dummies")
  install.packages("stringr")

  
  #load libraries
  library(data.table) 
  library(dplyr) 
  library(rdrobust) 
  library(lmtest) 
  library(ggplot2) 
  library(AER) 
  library(gridExtra)
  library(sandwich)
  library(dummies)
  library(stringr)


############################################################################################################################################# 

  
##### Functions (Always RUN before proceeding to Tables and Plots) ########################################################################## 
  
  .Weighting <- function(xx,kernel,zz){
    
    if(kernel > 0){
      if(kernel == 1){xx$wght <- zz - abs(xx$run)}
      if(kernel == 2){xx$wght <- 0.75*(1 - ((xx$run/zz)**2))}
      if(kernel == 3){xx$wght <- (1/((2*pi)**2))*exp(-0.5*((abs(xx$run/zz)**2)))}
      xx$wght[xx$t == 1] <- xx$wght[xx$t == 1] / sum(xx$wght[xx$t == 1])
      xx$wght[xx$t == 0] <- xx$wght[xx$t == 0] / sum(xx$wght[xx$t == 0])
    }else{xx$wght <- 1/nrow(xx)}
    return(xx)
  }
  
  .RDplot <- function(data,cut,band,bins,degree,x.title,y.title,title,con,sz,brk) {
    
    if(degree == 1){mm <- (var ~ Score2 )}
    if(degree == 2){mm <- (var ~ Score2 + I(Score2**2) )}
    if(degree == 3){mm <- (var ~ Score2 + I(Score2**2) + I(Score2**3) )}
    
    data <- subset(data, !is.na(var))
    
    data$Score2 <- data$run - cut 
    data <- subset(data, abs(Score2) <= band)
    vec <- seq(cut, band, length.out =  (bins+1))
    vec_mid <- vec[-length(vec)] + diff(vec)/2
    data$count <- 1 ;     i <- 0
    
    
    for (iii in 0:1){
      cc <- iii 
      if(iii == 0) cc <- -1
      aux <- subset(data, t == iii)
      aux$groups <- as.factor(cut(cc*aux$Score2,breaks=vec, include.lowest = TRUE))
      R <- group_by(aux,groups) %>% summarise (var = mean(var), count = sum(count) ) #%>% complete(groups)
      #R <- subset(R, !is.na(Var))
      R$t <- iii
      R$Score2 <- cc*vec_mid
      
      mdl <- lm(mm , data = aux) 
      pred <- predict(mdl, R, interval = "confidence", level = con, na.action = na.pass) 
      PRE <- pred[,1] ; R$pre <- PRE
      predSE <- predict(mdl, R, interval = "confidence", level =con, na.action = na.pass, se=TRUE)$se.fit
      t <- ((pred[1,1]-pred[1,2])/predSE[1])
      V <- as.matrix(vcov(mdl) )  
      
      if(degree == 1){X <- data.frame(1,R$Score2)}
      if(degree == 2){X <- data.frame(1,R$Score2,(R$Score2^2))}
      if(degree == 3){X <- data.frame(1,R$Score2,(R$Score2^2),(R$Score2^3))}
      
      X <- as.matrix(X) ; se_robust <- sqrt(diag(X %*% V %*% t(X)))
      LOW <- pred[,1] - t*se_robust ; HIGH <- pred[,1] + t*se_robust
      R$low <- LOW ;    R$high <- HIGH 
      
      if(iii == 0){R0 <- R ; plot_data <- R}else{R1 <- R ;plot_data <- rbind(plot_data,R)}
    }
    
    plot_data <- data.frame(plot_data)
    plot_data <- filter(plot_data, !is.na(count))
    plot_data$count2 <- plot_data$count/sum(plot_data$count)
    if(sz==0)  plot_data$count2 <- 1
    ymx <- max(plot_data$var)
    ymn <- min(plot_data$var)
    
    ggplot(data=plot_data, aes(x=Score2, y=var, ymax = ymx, ymin = ymn))   +   theme_bw() +
      theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
      geom_point( data=R0, aes(x=Score2, y=var, size=count), shape=16,  color = "gray35", bg="gray95") + #aes(size = count2/4)
      geom_point( data=R1, aes(x=Score2, y=var,size=count), shape=16, color = "gray65", bg="gray95") +
      geom_vline(xintercept = 0, colour="gray25", linetype = "longdash") +
      geom_line(data=R1, aes(x=Score2, y=pre),colour="gray65",  size=1.5, alpha=.75) +
      geom_line(data=R0, aes(x=Score2, y=pre),colour="gray35",  size=1.5, alpha=.75) +
      ggtitle(title) + 
      theme(plot.title = element_text(family = "A", size=12))+
      xlab(x.title) + ylab(y.title) +
      theme(axis.text = element_text(colour="black", size=12, family="A")) +
      theme(axis.title = element_text(colour="black", size=12, family="A")) +
      geom_ribbon(data=R0, aes(ymin=low,ymax=high),alpha=0.10) +
      geom_ribbon(data=R1, aes(ymin=low,ymax=high),alpha=0.10) +
      scale_x_continuous(breaks=brk) +
      theme(legend.position="none")
    
    
  }
  
  .Newplot <- function(data,r,v,xvar,minD,maxD,bins1,bins2,shift,bb,x.title,y.title,degree,multi,oneside,bb3){
    
    
    Di <- matrix(0,(bins1),3)
    Di[,1] <- seq(from=minD, to=maxD, length.out=(bins1))
    label <- paste("t",xvar,sep=":")
    
    for (i in 1:nrow(Di)){
      Di[i,2] <- r["t",1] + r[label,1]*Di[i,1] 
      Di[i,3] <-(  v["t","t"] + (Di[i,1]**2)*v[label,label] + 2*Di[i,1]*v["t",label] )^.5
    }
    
    MT <- data.frame(Di) ; names(MT) <- c("D","coeff","sd")
    MT$h <- MT$coeff+1.96*MT$sd
    MT$l <- MT$coeff-1.96*MT$sd  
    
    jazz <- data.frame(matrix(0,(bins2),2))
    xx <- seq(from=min(MT$D), to=(max(MT$D)), length.out=(bins2+1))
    
    data <- data.frame(data)
    data$x <- data[,match(xvar,names(data))]
    
    i <- 2
    
    for (i in 1:nrow(jazz)){
      top <- xx[i+1]
      bot <- xx[i]
      if(is.na(top))  top <- xx[i+1] + 1
      jj <- subset(data, x >= bot & x < top )
      if(oneside==1) jj <- subset(data, x >= bot & x < top & t == 1)
      if(oneside==1) {datax <- subset(data,  t == 1)}else{datax <- data}
      jazz[i,1] <- (xx[i]+xx[i+1])/2
      
      jazz[i,2] <- nrow(jj)/nrow(datax)
    }
    names(jazz) <- c("D","dens")
    
    bb2 <- bb+shift
    
    ggplot(data=MT, aes(x=D, y=coeff, ymin=0))   +    theme_bw() +
      theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
      geom_line(data=MT, aes(x=D, y=coeff+shift),colour="gray10",  size=1, alpha=.75) +
      theme(plot.title = element_text(family = "A", size=13))+
      geom_hline(yintercept=(0+shift), lty=3)+
      xlab(x.title) + ylab(y.title) +
      theme(axis.text = element_text(colour="black", size=13, family="A")) +
      theme(axis.title = element_text(colour="black", size=13, family="A")) +
      
      geom_line(data=MT, aes(x=D, y=h+shift),colour="gray10",  linetype="dashed",size=.75, alpha=.75) +
      geom_line(data=MT, aes(x=D, y=l+shift),colour="gray10",  linetype="dashed",size=0.75, alpha=.75) +
      #geom_ribbon(data=MT, aes(ymin=l+shift,ymax=h+shift),alpha=0.2, fill) +
      
      geom_bar(data=jazz, aes(x=D, y=dens*multi, group = 1), stat="identity", position="dodge",
               size =0.1,color="gray35",fill="gray85", alpha=0.3) +
      scale_y_continuous(breaks=bb2, labels=bb )+
      scale_x_continuous(breaks=bb3)+
      coord_cartesian(ylim=c(bb2[1],bb2[length(bb2)]))
  }


############################################################################################################################################# 

  
##### Setup (Always RUN before proceeding to Tables and Plots) ############################################################################## 
  
  # set active R directory here with setwd() function
  #setwd("")
  
  # set fonts for plots
  windowsFonts( A=windowsFont("Liberation Sans")) ; par(family="A") ; sz <- 11

  # Set sortcuts for regression formulas
  base_for <- "var ~  vari + run + trun + factor(cut) "
  base_for2 <- "var ~  vari + run + trun  + factor(cut) + factor(sta)"
  base_for2a <- "var ~  vari + run + I(run^2) + trun  + (trun^2) + factor(cut) + factor(sta)"
  base_for2b <- "var ~  vari + run + I(run^2)+I(run^3) + trun  + (trun^2) +(trun^3)+ factor(cut) + factor(sta)"
  cov1 <- "+ men + urb  + p_budget +hepc+ poor1 + poor2 + desert + able + gdp + metr  + liter "
  cov2 <- "  + base.p + p11 + p12 + p13 + p15 + p40 + p45 + p55  "
  iv <- "| .-vari  + t"

  maindata <- fread("data_main.csv")
  olddata <- read.csv("data_old.csv")
  maindata$trun <- maindata$t * maindata$run

  # Creates dummies for the mayor's party
  mainparties <- c(11,12,13,15,40,45,55)
  for (i in 1:length(mainparties)){
    newvar <- paste0("p",mainparties[i])
    maindata$newvar <- ifelse(maindata$m.party == mainparties[i],1,0)
    names(maindata)[ncol(maindata)] <- newvar
  }
  
  aux <- maindata %>% select(ibge, seats, cut, t, run, trun, sta,men,urb,poor1,poor2,desert,metr,liter  )
  olddata <- merge(olddata,aux,by="ibge")
  
  mainparties <- c(11,12,13,15,40,45)
  for (i in 1:length(mainparties)){
    newvar <- paste0("p",mainparties[i])
    olddata$newvar <- ifelse(olddata$m.party == mainparties[i],1,0)
    names(olddata)[ncol(olddata)] <- newvar
  }
  
  covars1 <- dummy(maindata$cut, sep = ".")
  covars <- covars1[,2:(ncol(covars1))]
  
  b1 <- rdbwselect(maindata$seats, maindata$run, c = 0, p=1, q=2,  kernel = "tri", bwselect = "cerrd" , covs=covars)$bws ; b1
  b2 <- rdbwselect(maindata$seats, maindata$run, c = 0, p=2, q=4,  kernel = "tri", bwselect = "cerrd" , covs=covars)$bws ; b2
  b3 <- rdbwselect(maindata$seats, maindata$run, c = 0, p=3, q=5,  kernel = "tri", bwselect = "cerrd" , covs=covars)$bws ; b3  
  
  
  
############################################################################################################################################# 
  
 
##### Table A1: Maximum number of council members, by population ############################################################################
  
  
  cut <- c(15,30,50,80,120,160,300,450,600,750,900,1050,1200,1350,1500,1800,2400,3000,4000,5000,6000,7000,8000)
  cuts2 <- c(11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55)
  
  jazz <- data.frame(cut,cuts2)
  
  data_aux <- maindata

  data_aux$x <- 1
  dataz <- subset(data_aux, abs(run) <= 7.5  )
  d <- group_by(dataz,cut,t) %>% summarise(count=sum(x))
  d1 <- subset(d, t == 1) ; d0 <- subset(d, t == 0)
  jazz <- left_join(jazz,d0,by="cut")
  jazz <- left_join(jazz,d1,by="cut")
  jazz[is.na(jazz)] <- 0
  jazz$t.x <- jazz$t.y <- NULL
  
  jazz$perc <- paste0( format(round((jazz$cuts2 / (jazz$cuts2-2)-1)*100,1),nsmall=1  ), "%")
  jazz <- jazz[,c(1,2,5,3,4)]

  #### For pasting in latex
  for (i in 1:ncol(jazz)){
    fake <- data.frame(matrix("&",nrow(jazz),1))
    x <- cbind(fake,jazz[,i])
    if(i == 1) {xx <- x}else{xx <- cbind(xx,x)}
  }
  #row.names(xx) <- c("RD Effect","","Pre-Treatment Mean","Bandwidth","Observations")
  xx[,ncol(xx)+1] <- c("\tabularnewline","\tabularnewline","\tabularnewline","\tabularnewline","\tabularnewline",
                       "\tabularnewline","\tabularnewline","\tabularnewline","\tabularnewline","\tabularnewline",
                       "\tabularnewline","\tabularnewline","\tabularnewline","\tabularnewline","\tabularnewline",
                       "\tabularnewline","\tabularnewline","\tabularnewline","\tabularnewline","\tabularnewline",
                       "\tabularnewline","\tabularnewline","\tabularnewline[0.25cm]")
  names(xx) <- NULL
  xx <- xx[,-c(1,2)]
  row.names(xx) <- cut
  print(xx) 
  
  

############################################################################################################################################# 
  
  
##### Table A2: RD effects in the first stage ###############################################################################################
  
  data_aux <- maindata
  data_aux$var <- (data_aux$seats)
  
  res <- data.frame(matrix(0,5,5))
  
  for (i in 1:5){
    
    formul <- as.formula("var ~  t*run+factor(cut)")
    
    if(i <= 2) band <- b1[1]
    if(i == 2) formul <- as.formula(paste("var ~  t*run +factor(cut)+factor(sta)",cov1,sep=""))
    if(i == 3) band <- b1[2]*.5
    
    if(i == 4) band <- min(7.5,b2[2]*1)
    if(i == 5) band <- min(7.5,b3[2]*1)
    
    
    datax <- subset(data_aux, abs(run) < band & cut <= 300  )  
    datax <- .Weighting(datax,1,band) ; datax0 <- subset(datax, t == 0)
   
    reg <- lm(formul  , weights=wght  ,data=datax) 
    r <- coeftest(reg,  vcov = vcovHC(reg, type="HC3")) 
    reg <- lm(var ~  run  , weights=wght  ,data=datax0) 
    r2 <- coeftest(reg,  vcov = vcovHC(reg, type="HC3")) 
    
    if(i == 4){
      reg <- lm(var ~  t*run + t*I(run^2)+factor(cut), weights=wght  ,data=datax) 
      r <- coeftest(reg,  vcov = vcovHC(reg, type="HC3")) 
      reg <- lm(var ~  run + I(run^2) , weights=wght  ,data=datax0) 
      r2 <- coeftest(reg,  vcov = vcovHC(reg, type="HC3")) 
    }
    if(i == 5){
      reg <- lm("var ~  t*run+ t*I(run^2)+ t*I(run^3) +factor(cut)", weights=wght  ,data=datax) 
      r <- coeftest(reg,  vcov = vcovHC(reg, type="HC3")) 
      reg <- lm(var ~  run + I(run^2)+ I(run^3) , weights=wght  ,data=datax0) 
      r2 <- coeftest(reg,  vcov = vcovHC(reg, type="HC3")) 
    }
    
    tv <- abs(r[2,3])
    stars <- "" ; if(tv >= 1.645){stars <- "�"} ; if(tv >= 1.96){stars <- "*"} 
    coeff <- round(r[2,1],3) ; sd <- round(r[2,2],3) ; baseline <- round(r2[1,1],3)
    
    res[1,i] <- paste(format(coeff,nsmall=3),stars,sep="")
    res[2,i] <- paste("(",format(sd,nsmall=3),")",sep="")
    res[3,i] <- paste(format(baseline,nsmall=3),sep="")
    res[4,i] <- format(round(band,2),nsmall=2)
    res[5,i] <- nrow(datax)
  }

  #### For pasting in LatEx
  for (i in 1:ncol(res)){
    fake <- data.frame(matrix("&",nrow(res),1))
    x <- cbind(fake,res[,i])
    if(i == 1) {xx <- x}else{xx <- cbind(xx,x)}
  }
  row.names(xx) <- c("RD Effect","","Pre-Treatment Mean","Bandwidth","Observations")
  xx[,ncol(xx)+1] <- c("\tabularnewline","\tabularnewline[0.25cm]","\tabularnewline[0.25cm]","\tabularnewline","\tabularnewline[0.25cm]")
  names(xx) <- NULL
  print(xx) 
  
############################################################################################################################################# 
  
  
##### Table A3: Balance of covariates #######################################################################################################
  
  
  data_aux <- maindata
  data_aux$vari <- (data_aux$seats)
  
  band <- round(b1[1],2)

  vec <- str_replace_all(cov1," ","")
  vec <- unlist(str_split(vec,"[+]"))
  vec <- vec[2:length(vec)]
  
  res <- data.frame(matrix(0,length(vec)*2,3)) 
  
  for (i in 1:3){
    for(j in 1:length(vec)){
      band <- round(b1[1],2)
      
      vecc <- vec[-j]
      cov3 <- paste(" + ",vecc, sep="", collapse="") 
      
      if(i == 1)  formul <- as.formula(paste(base_for,iv,sep=""))
      if(i == 2)  formul <- as.formula(paste(base_for2,iv,sep="")) 
      if(i == 3)  formul <- as.formula(paste(base_for2,cov3,iv,sep="")) 
      
      num <- match(vec[j],names(data_aux))
      data_aux$var <- data_aux[[num]]
      
      datax <- subset(data_aux, abs(run) <= band & cut <= 300   )
      datax <- .Weighting(datax,1,band)
      
      reg <- ivreg(formul  , weights=wght, data=datax) 
      r <- coeftest(reg,  vcov = vcovHC(reg, type="HC3"))[2,]

      tv <- abs(r[3])
      stars <- "" ; if(tv >= 1.645){stars <- "�"} ; if(tv >= 1.96){stars <- "*"} 
      coeff <- round(r[1],3) ; sd <- round(r[2],3) 
      
      res[j*2-1,i] <- paste(format(coeff,nsmall=3),stars,sep="")
      res[j*2-0,i] <- paste("(",format(sd,nsmall=3),")",sep="")

    }
  }

  #### For pasting in LaTeX
  for (i in 1:ncol(res)){
    fake <- data.frame(matrix("&",nrow(res),1))
    x <- cbind(fake,res[,i])
    if(i == 1) {xx <- x}else{xx <- cbind(xx,x)}
  }
  
  xx[,ncol(xx)+1] <- "\tabularnewline"
  xx[nrow(xx),ncol(xx)] <- "\tabularnewline[0.25cm]"
  row.names(xx) <-  c("Gender share","(2010 census)","Urban share","(2010 census) ","Past pc budget ",
                      "(log)  ","Health and Education spending","(past share of budget)","Garbage collection","(2010 census)   ",
                      "Piped Water","(2010 census)    ","Semi-arid location","(binary, 1=semi-arid)      ","2012 pc GDP","(log)       ",
                      "Number of voters","(log)        ",
                      "Metropolitan area","(binary, 1=metropolitan)            ",
                      "Literacy rate","(2010 census)        ")
  names(xx) <- NULL
  print(xx) 
  
  
  
############################################################################################################################################# 
  
  
##### Table A4: Correlation between council size and mayors partisanship at the discontinuity ###############################################

  data_aux <- maindata
  data_aux$vari <- (data_aux$seats)
  band <- round(b1[1],2)
  
  vec <- c("base.p","p13","p15","p45","p55","p40","p11","p12")
  
  res <- data.frame(matrix(0,length(vec)*2,3)) 
  for (i in 1:3){
    for(j in 1:length(vec)){
      band <- round(b1[1],2)
      
      vecc <- vec[-j]
      cov3 <- paste(" + ",vecc, sep="", collapse="") 
      
      if(i == 1)  formul <- as.formula(paste(base_for,iv,sep=""))
      if(i == 2)  formul <- as.formula(paste(base_for2,cov1,iv,sep="")) 
      if(i == 3)  formul <- as.formula(paste(base_for2,cov1,cov3,iv,sep="")) 
      
      num <- match(vec[j],names(data_aux))
      data_aux$var <- data_aux[[num]]
      
      datax <- subset(data_aux, abs(run) <= band & cut <= 300   )
      datax <- .Weighting(datax,1,band)
      
      reg <- ivreg(formul  , weights=wght, data=datax) 
      r <- coeftest(reg,  vcov = vcovHC(reg, type="HC3"))[2,]
   
      tv <- abs(r[3])
      stars <- "" ; if(tv >= 1.645){stars <- "�"} ; if(tv >= 1.96){stars <- "*"} 
      coeff <- round(r[1],3) ; sd <- round(r[2],3) 
      
      res[j*2-1,i] <- paste(format(coeff,nsmall=3),stars,sep="")
      res[j*2-0,i] <- paste("(",format(sd,nsmall=3),")",sep="")

    }
  }

  
  #### For pasting in latex
  for (i in 1:ncol(res)){
    fake <- data.frame(matrix("&",nrow(res),1))
    x <- cbind(fake,res[,i])
    if(i == 1) {xx <- x}else{xx <- cbind(xx,x)}
  }
  
  xx[,ncol(xx)+1] <- "\tabularnewline"
  xx[nrow(xx),ncol(xx)] <- "\tabularnewline[0.25cm]"
  row.names(xx) <-  c("PT's federal coalition","","PT mayor"," ","PMDB mayor","  ","PSDB mayor","   ",
                      "PSD mayor","    ","PSB mayor","     ","PP mayor","      ","PDT mayor","       ")
  names(xx) <- NULL
  print(xx) 
  
  
  
############################################################################################################################################# 
  
  
##### Table A5: Loss of electoral strength by the local incumbent party (excludes: 50, 300 pop) #############################################
  
  data_aux <- maindata
  data_aux$vari <- (data_aux$seats)
  band <- round(b1[1],2)
  
  res <- data.frame(matrix(0,12,3)) 
  
  for (i in 1:3){
    for(j in 1:4){
      
      if(i == 1)  formul <- as.formula(paste(base_for2,cov1,cov2,iv,sep=""))
      if(i == 2)  formul <- as.formula(paste(base_for2,cov1,iv,sep="")) 
      if(i == 3)  formul <- as.formula(paste(base_for2,iv,sep="")) 
      
      if(j == 1) {data_aux$s <- data_aux$g.support*data_aux$p.support*data_aux$f.support 
                            data_aux$var <- data_aux$indx*100 ; min_fcand <- 1}
      if(j == 2) {data_aux$s <- data_aux$g.support ; data_aux$var <- data_aux$g.pc*100 ; min_fcand <- 0}
      if(j == 3) {data_aux$s <- data_aux$p.support ; data_aux$var <- data_aux$p.pc*100 ; min_fcand <- 0}
      if(j == 4) {data_aux$s <- data_aux$f.support ; data_aux$var <- data_aux$f.pc*100 ; min_fcand <- 1}
      
      datax <- subset(data_aux, abs(run) <= band & s == 1 & f.cand > min_fcand & cut <= 300 & !cut %in% c(50,300) )
      datax <- .Weighting(datax,1,band)
      
      reg <- ivreg(formul  , weights=wght, data=datax) 
      r <- coeftest(reg,  vcov = vcovHC(reg), type="HC3")[2,]

      tv <- abs(r[3])
      stars <- "" ; if(tv >= 1.645){stars <- "�"} ; if(tv >= 1.96){stars <- "*"} 
      coeff <- round(r[1],3) ; sd <- round(r[2],3) 
      
      res[j*3-2,i] <- paste(format(coeff,nsmall=3),stars,sep="")
      res[j*3-1,i] <- paste("(",format(sd,nsmall=3),")",sep="")
 
      res[j*3,i] <- nrow(datax)
 
    }
  }

  
  #### For pasting in LaTex
  for (i in 1:ncol(res)){
    fake <- data.frame(matrix("&",nrow(res),1))
    x <- cbind(fake,res[,i])
    if(i == 1) {xx <- x}else{xx <- cbind(xx,x)}
  }
  last <-  c("\tabularnewline","\tabularnewline","\tabularnewline[0.25cm]")
  xx[,ncol(xx)+1] <- c(last,last,last,last)
  row.names(xx) <- c("Vote Share Index","(aggregates the elections below) ","Observations    ","Gubernatorial ","(2014)","Observations","Presidential ","(2014) ","Observations ",
                     "Mayoral","(2016)","Observations   ") ;  names(xx) <- NULL
  print(xx) 
  

############################################################################################################################################# 
  
  
##### Table A6: Loss of electoral strength by the local incumbent party (includes: 15 pop) ##################################################

  xbase_for2 <- "var ~  vari + run + trun  + factor(sta)"

  data_aux <- maindata
  data_aux$vari <- (data_aux$seats)
  band <- round(b1[1],2)
  
  res <- data.frame(matrix(0,12,3)) 
  
  for (i in 1:3){
    for(j in 1:4){
      
      if(i == 1)  formul <- as.formula(paste(xbase_for2,cov1,cov2,iv,sep=""))
      if(i == 2)  formul <- as.formula(paste(xbase_for2,cov1,iv,sep="")) 
      if(i == 3)  formul <- as.formula(paste(xbase_for2,iv,sep="")) 
      
      if(j == 1) {data_aux$s <- data_aux$g.support*data_aux$p.support*data_aux$f.support 
      data_aux$var <- data_aux$indx*100 ; min_fcand <- 1}
      if(j == 2) {data_aux$s <- data_aux$g.support ; data_aux$var <- data_aux$g.pc*100 ; min_fcand <- 0}
      if(j == 3) {data_aux$s <- data_aux$p.support ; data_aux$var <- data_aux$p.pc*100 ; min_fcand <- 0}
      if(j == 4) {data_aux$s <- data_aux$f.support ; data_aux$var <- data_aux$f.pc*100 ; min_fcand <- 1}
      
      datax <- subset(data_aux, abs(run) <= band & s == 1 & f.cand > min_fcand & cut == 15 )
      datax <- .Weighting(datax,1,band)
      
      reg <- ivreg(formul  , weights=wght, data=datax) 
      r <- coeftest(reg,  vcov = vcovHC(reg), type="HC3")[2,]
      
      tv <- abs(r[3])
      stars <- "" ; if(tv >= 1.645){stars <- "�"} ; if(tv >= 1.96){stars <- "*"} 
      coeff <- round(r[1],3) ; sd <- round(r[2],3) 
      
      res[j*3-2,i] <- paste(format(coeff,nsmall=3),stars,sep="")
      res[j*3-1,i] <- paste("(",format(sd,nsmall=3),")",sep="")
      
      res[j*3,i] <- nrow(datax)
      
    }
  }
  
  
  #### For pasting in LaTex
  for (i in 1:ncol(res)){
    fake <- data.frame(matrix("&",nrow(res),1))
    x <- cbind(fake,res[,i])
    if(i == 1) {xx <- x}else{xx <- cbind(xx,x)}
  }
  last <-  c("\tabularnewline","\tabularnewline","\tabularnewline[0.25cm]")
  xx[,ncol(xx)+1] <- c(last,last,last,last)
  row.names(xx) <- c("Vote Share Index","(aggregates the elections below) ","Observations    ","Gubernatorial ","(2014)","Observations","Presidential ","(2014) ","Observations ",
                     "Mayoral","(2016)","Observations   ") ;  names(xx) <- NULL
  print(xx) 
  
  
  
  
############################################################################################################################################# 
  
  
##### Table A7: Loss of electoral strength by the local incumbent party (placebo) ###########################################################
  

  data_aux <- olddata
  data_aux$vari <- (data_aux$seats)
  band <- round(b1[1],2)

  res <- data.frame(matrix(0,12,3)) 
  cov2x <- "  + base.p + p12 + p13 + p15 + p40 + p45 "
  
  for (i in 1:3){
    for(j in 1:4){

      if(i == 1)  formul <- as.formula(paste(base_for2,cov1,cov2x,iv,sep=""))
      if(i == 2)  formul <- as.formula(paste(base_for2,cov1,iv,sep="")) 
      if(i == 3)  formul <- as.formula(paste(base_for2,iv,sep="")) 
      
      if(j == 1) {data_aux$s <- data_aux$g.support*data_aux$p.support*data_aux$f.support 
                          data_aux$var <- data_aux$indx*100 ; min_fcand <- 1}
      if(j == 2) {data_aux$s <- data_aux$g.support ; data_aux$var <- data_aux$g.pc*100 ; min_fcand <- 0}
      if(j == 3) {data_aux$s <- data_aux$p.support ; data_aux$var <- data_aux$p.pc*100 ; min_fcand <- 0}
      if(j == 4) {data_aux$s <- data_aux$f.support ; data_aux$var <- data_aux$f.pc*100 ; min_fcand <- 1}
      
      datax <- subset(data_aux, abs(run) <= band & s == 1 & f.cand > min_fcand & cut <= 300 )
      datax <- .Weighting(datax,1,band)
      
      reg <- ivreg(formul  , weights=wght, data=datax) 
      r <- coeftest(reg,  vcov = vcovHC(reg), type="HC3")[2,]
      
      summary(reg)
      
      tv <- abs(r[3])
      stars <- "" ; if(tv >= 1.645){stars <- "�"} ; if(tv >= 1.96){stars <- "*"} 
      coeff <- round(r[1],3) ; sd <- round(r[2],3) 
      
      res[j*3-2,i] <- paste(format(coeff,nsmall=3),stars,sep="")
      res[j*3-1,i] <- paste("(",format(sd,nsmall=3),")",sep="")
      
      
      res[j*3,i] <- nrow(datax)
      
      
    }
  }

  #### For pasting in latex
  for (i in 1:ncol(res)){
    fake <- data.frame(matrix("&",nrow(res),1))
    x <- cbind(fake,res[,i])
    if(i == 1) {xx <- x}else{xx <- cbind(xx,x)}
  }
  last <-  c("\tabularnewline","\tabularnewline","\tabularnewline[0.25cm]")
  xx[,ncol(xx)+1] <- c(last,last,last,last)
  row.names(xx) <- c("Vote Share Index","(aggregates the elections below) ","Observations    ",
                     "Gubernatorial ","(2010)","Observations",
                     "Presidential ","(2010) ","Observations ",
                     "Mayoral","(2012)","Observations   ") ;  names(xx) <- NULL
  names(xx) <- NULL
  print(xx) 
  
  
############################################################################################################################################# 
  
  
##### Table A8: Other Political Outcomes ####################################################################################################
  
  data_aux <- maindata
  data_aux$vari <- (data_aux$seats)
  band <- round(b1[1],2)
  
  data_aux$major.g <- data_aux$mg.team/data_aux$m.team
  data_aux$major.p <- data_aux$mp.team/data_aux$m.team
  data_aux$rerun2 <- data_aux$rerun/data_aux$seats
  data_aux$coal.reelec <- data_aux$mre.team/data_aux$mr.team
  data_aux$all.reelec <- data_aux$re.team/data_aux$rerun
  
  vec <- c("cand","m.pc","size","major.g","major.p","cand16","pc16","size16","rerun2","all.reelec","coal.reelec","f.support")
  
  res <- data.frame(matrix(0,length(vec)*2,3)) 
  
  for (i in 1:3){
    for(j in 1:length(vec)){

      vecc <- vec[-j]
      cov3 <- paste(" + ",vecc, sep="", collapse="") 
      
      if(i == 1)  formul <- as.formula(paste(base_for,iv,sep=""))
      if(i == 2)  formul <- as.formula(paste(base_for2,cov1,iv,sep="")) 
      if(i == 3)  formul <- as.formula(paste(base_for2,cov1,cov3,iv,sep="")) 
      
      num <- match(vec[j],names(data_aux))
      data_aux$var <- data_aux[[num]]
      
      datax <- subset(data_aux, abs(run) <= band & cut <= 300   )
      datax <- .Weighting(datax,1,band)
      
      reg <- ivreg(formul  , weights=wght, data=datax) 
      r <- coeftest(reg,  vcov = vcovHC(reg, type="HC3"))[2,]
   
      tv <- abs(r[3])
      stars <- "" ; if(tv >= 1.645){stars <- "�"} ; if(tv >= 1.96){stars <- "*"} 
      coeff <- round(r[1],3) ; sd <- round(r[2],3) 
      
      res[j*2-1,i] <- paste(format(coeff,nsmall=3),stars,sep="")
      res[j*2-0,i] <- paste("(",format(sd,nsmall=3),")",sep="")
      
    }
  }
  res
  
  #### For pasting in latex
  for (i in 1:ncol(res)){
    fake <- data.frame(matrix("&",nrow(res),1))
    x <- cbind(fake,res[,i])
    if(i == 1) {xx <- x}else{xx <- cbind(xx,x)}
  }
  
  xx[,ncol(xx)+1] <- "\tabularnewline"
  xx[c(nrow(xx)-14, nrow(xx)),ncol(xx)] <- "\tabularnewline[0.25cm]"
  row.names(xx) <-  c("Mayoral candidates","(number)","Mayor's vote ","(pct)",
                      "Parties in the winning coalition","(log)  ","Share of elected coalition councilors aligned ","(with mayor's 2014 gubernatorial coalition) ",
                      "Share of elected coalition councilors aligned","(with mayor's 2014 presidential coalition) ",
                      "Mayoral candidates ","(number)       ","Mayor's vote","(pct)         ",
                      "Parties in the winning coalition "," (log)    ",
                      "Share of councilors that run again in 2016","(of all elected)",
                      "Share of reelected councilors","(of the ones that run in 2016)",
                      "Share of reelected coalition councilors","(of the ones that run in 2016) ",
                      "Incumbent Party does not participate ","(binary variable, 1=does not participate)")
  names(xx) <- NULL
  print(xx) 
  
  
  
  
  
############################################################################################################################################# 
  
  
##### Table A9: Loss of electoral strength by the local incumbent party (robustness) ########################################################
  
  data_aux <- maindata
  data_aux$vari <- (data_aux$seats)
  band <- round(b1[1],2)
  
  
  res <- data.frame(matrix(0,12,4)) 
  
  for (i in 1:4){
    for(j in 1:4){

      if(i == 3)  band <- round(b2[1],3)
      if(i == 4)  band <- min(round(b3[1],2),7.5)
      
      if(i == 2)  formul <- as.formula(paste(base_for2,cov1,cov2,iv,sep=""))
      if(i == 3)  formul <- as.formula(paste(base_for2a,cov1,cov2,iv,sep=""))
      if(i == 4)  formul <- as.formula(paste(base_for2b,cov1,cov2,iv,sep=""))
      if(i == 1)  formul <- as.formula(paste("var ~  t + run + trun  + factor(cut) + factor(sta)",cov1,cov2,sep=""))
      
      if(j == 1) {data_aux$s <- data_aux$g.support*data_aux$p.support*data_aux$f.support ; data_aux$var <- data_aux$indx*100 ; min_fcand <- 1}
      if(j == 2) {data_aux$s <- data_aux$g.support ; data_aux$var <- data_aux$g.pc*100 ; min_fcand <- 0}
      if(j == 3) {data_aux$s <- data_aux$p.support ; data_aux$var <- data_aux$p.pc*100 ; min_fcand <- 0}
      if(j == 4) {data_aux$s <- data_aux$f.support ; data_aux$var <- data_aux$f.pc*100 ; min_fcand <- 1}
      
      datax <- subset(data_aux, abs(run) <= band & s == 1 & f.cand > min_fcand & cut <= 300 & !is.na(var)   )
      datax <- .Weighting(datax,1,band)
      
      if(i == 1) reg <- lm(formul  , weights=wght, data=datax) 
      if(i > 1)  reg <- ivreg(formul  , weights=wght, data=datax) 

      r <- coeftest(reg,  vcov = vcovHC(reg, type="HC3"))[2,]
      
      tv <- abs(r[3])
      stars <- "" ; if(tv >= 1.645){stars <- "�"} ; if(tv >= 1.96){stars <- "*"} 
      coeff <- round(r[1],3) ; sd <- round(r[2],3) 
      
      res[j*3-2,i] <- paste(format(coeff,nsmall=3),stars,sep="")
      res[j*3-1,i] <- paste("(",format(sd,nsmall=3),")",sep="")

      res[j*3,i] <- nrow(datax)
  
    }
  }

  
  #### For pasting in latex
  for (i in 1:ncol(res)){
    fake <- data.frame(matrix("&",nrow(res),1))
    x <- cbind(fake,res[,i])
    if(i == 1) {xx <- x}else{xx <- cbind(xx,x)}
  }
  last <-  c("\tabularnewline","\tabularnewline","\tabularnewline[0.25cm]")
  xx[,ncol(xx)+1] <- c(last,last,last,last)
  row.names(xx) <- c("Vote Share Index","(aggregates the elections below) ","Observations    ",
                     "Gubernatorial ","(2014)","Observations","Presidential ","(2014) ","Observations ",
                     "Mayoral","(2016)","Observations   ") ;  names(xx) <- NULL
  names(xx) <- NULL
  print(xx) 
  
  
  
  
############################################################################################################################################# 
  
  
##### Table A10: Loss of electoral strength by the local incumbent party (with congress) ####################################################
  
  data_aux <- maindata
  data_aux$vari <- (data_aux$seats)
  band <- round(b1[1],2)
  
  res <- data.frame(matrix(0,15,3)) 
  
  for (i in 1:3){
    for(j in 1:5){
      
      if(i == 1)  formul <- as.formula(paste(base_for2,cov1,cov2,iv,sep=""))
      if(i == 2)  formul <- as.formula(paste(base_for2,cov1,iv,sep="")) 
      if(i == 3)  formul <- as.formula(paste(base_for2,iv,sep="")) 
      
      if(j == 1) {data_aux$s <- data_aux$g.support*data_aux$p.support*data_aux$d.support*data_aux$f.support
                     data_aux$var <- data_aux$indx2*100 ; min_fcand <- 0}
  
      if(j == 2) {data_aux$s <- data_aux$g.support ; data_aux$var <- data_aux$g.pc*100 ; min_fcand <- 0}
      if(j == 3) {data_aux$s <- data_aux$p.support ; data_aux$var <- data_aux$p.pc*100 ; min_fcand <- 0}
      if(j == 4) {data_aux$s <- data_aux$f.support ; data_aux$var <- data_aux$f.pc*100 ; min_fcand <- 1}
      if(j == 5) {data_aux$s <- data_aux$d.support ; data_aux$var <- data_aux$d.pc*100 ; min_fcand <- 0}
      
      datax <- subset(data_aux, abs(run) <= band & s == 1 & f.cand > min_fcand & cut <= 300 )
      datax <- .Weighting(datax,1,band)
      
      reg <- ivreg(formul  , weights=wght, data=datax) 
      r <- coeftest(reg,  vcov = vcovHC(reg), type="HC3")[2,]

      tv <- abs(r[3])
      stars <- "" ; if(tv >= 1.645){stars <- "�"} ; if(tv >= 1.96){stars <- "*"} 
      coeff <- round(r[1],3) ; sd <- round(r[2],3) 
      
      res[j*3-2,i] <- paste(format(coeff,nsmall=3),stars,sep="")
      res[j*3-1,i] <- paste("(",format(sd,nsmall=3),")",sep="")
      
      
      res[j*3,i] <- nrow(datax)

    }
  }
  
  
  #### For pasting in latex
  for (i in 1:ncol(res)){
    fake <- data.frame(matrix("&",nrow(res),1))
    x <- cbind(fake,res[,i])
    if(i == 1) {xx <- x}else{xx <- cbind(xx,x)}
  }
  last <-  c("\tabularnewline","\tabularnewline","\tabularnewline[0.25cm]")
  
  xx[,ncol(xx)+1] <- c(last,last,last,last,last)
  row.names(xx) <- c("Vote Share Index", "(aggregates the elections below)",
                     "Observations    ",
                     "Gubernatorial ","(2014)","Observations","Presidential ","(2014) ","Observations ",
                     "Mayoral","(2016)","Observations   ","Congressional ","(2014)  ","Observations       ") ;  names(xx) <- NULL
  
  
  names(xx) <- NULL
  print(xx) 
  
  
  
############################################################################################################################################# 
  
  
##### Table A11: Heterogeneity of electoral effects, by budget ##############################################################################
  
  data_aux <- maindata
  data_aux$vari <- (data_aux$seats)
  band <- round(b1[1],2)
  
  base_for_i <- "var ~  vari + ivari  + i + run + trun + irun + itrun + factor(cut) + factor(sta)"
  iv_i <- "| .-vari -ivari  + t + it"
  formul <- as.formula(paste(base_for_i,cov1,cov2,iv_i,sep=""))
  
  res <- data.frame(matrix(0,6,4)) 

  
  for (i in 1:4){

    
    if(i %in% c(1,3))  {data_aux$s <- data_aux$g.support ; data_aux$var <- data_aux$g.pc*100 ; min_fcand <- 0}
    if(i %in% c(2,4))  {data_aux$s <- data_aux$p.support ; data_aux$var <- data_aux$p.pc*100 ; min_fcand <- 0}
    
    datax <- subset(data_aux, abs(run) <= band & s == 1 & f.cand > min_fcand & cut <= 300 & !is.na(var)   )
    datax <- .Weighting(datax,1,band)
    
    if(i %in% c(1,2)) {  datax <- subset(datax, rev >=0 & rev != Inf)
    datax$j <- summary(lm( datax$rev ~factor(datax$cut) + log(datax$pop) + factor(datax$sta)))$res
    med <- round(median(datax$j[!is.na(datax$j)]),5)}
    
    if(i %in% c(1,2)) {datax$i <- 0 ; datax$i[datax$j >= med] <- 1}
    if(i %in% c(3,4)) {datax$i <- datax$base.g*datax$base.p }
    
    datax$ivari <- datax$i*datax$vari
    datax$it <- datax$i*datax$t
    datax$itrun <- datax$i*datax$t*datax$run
    datax$irun <- datax$i*datax$run
    
    reg <- ivreg(formul  , weights=wght, data=datax) ;  coeftest(reg,  vcov = vcovHC(reg, type="HC3"))
    r <- coeftest(reg,  vcov = vcovHC(reg, type="HC3"))[2:3,] ; v <- vcovHC(reg, type="HC3")
    
    tv <- abs(r[1,3])
    stars <- "" ; if(tv >= 1.645){stars <- "�"} ; if(tv >= 1.96){stars <- "*"} 
    coeff <- round(r[1,1],3) ; sd <- round(r[1,2],3) 
    
    res[1,i] <- paste(format(coeff,nsmall=3),stars,sep="")
    res[2,i] <- paste("(",format(sd,nsmall=3),")",sep="")
    res[3,i] <- nrow(datax)-sum(datax$i)
    
    coeff <- r[1,1]+r[2,1]  ;  sd <- (v[2,2]  + v[3,3]  + 2*v[2,3] )^.5
    tv <- abs(coeff/sd)
    coeff <- round(coeff,3) ; sd <- round(sd,3) 
    stars <- "" ; if(tv >= 1.645){stars <- "�"} ; if(tv >= 1.96){stars <- "*"} 
    
    res[4,i] <- paste(format(coeff,nsmall=3),stars,sep="")
    res[5,i] <- paste("(",format(sd,nsmall=3),")",sep="")
    
    res[6,i] <- sum(datax$i)
    
  }
  res
  
  
  #### For pasting in latex
  for (i in 1:ncol(res)){
    fake <- data.frame(matrix("&",nrow(res),1))
    x <- cbind(fake,res[,i])
    if(i == 1) {xx <- x}else{xx <- cbind(xx,x)}
  }
  last <-  c("\tabularnewline","\tabularnewline","\tabularnewline[0.25cm]")
  xx[,ncol(xx)+1] <- c(last,last)
  row.names(xx) <- c("Low Budget Sample","    ","Observations    ","High Budget Sample","","Observations   ")
  names(xx) <- NULL
  print(xx) 
  
  
  
  
############################################################################################################################################# 
  
  
##### Figure A1: Heterogeneity in electoral losses, by status in higher coalitions ##########################################################  
  
  data_aux <- maindata
  data_aux$vari <- (data_aux$seats)
  band <- round(b1[1],2)
  
  base_for_i <- "var ~  vari + ivari  + i + run + trun + irun + itrun + factor(cut) + factor(sta)"
  iv_i <- "| .-vari -ivari  + t + it"
  
  formul <- as.formula(paste(base_for_i,cov1,cov2,iv_i,sep=""))
  formulx <- as.formula(paste(base_for2,cov1,cov2,iv,sep=""))
  max_cut <- 300

  
  for (i in 1:2){
    
    res <- data.frame(matrix(0,3,2)) 
    if(i==1) {data_aux$s <- data_aux$g.support ; data_aux$var <- data_aux$g.pc*100}
    if(i==2) {data_aux$s <- data_aux$p.support ; data_aux$var <- data_aux$p.pc*100}
    
    datax <- subset(data_aux, abs(run) <= band & s == 1 & f.cand > 0 & cut <= 300 )
    datax <- .Weighting(datax,1,band)
    
    if(i==1) {datax$i <- 0 ; datax$i[datax$m.party == datax$g.party | datax$m.party == datax$g.vice] <- 1}
    
    if(i==2) { datax$i <- 0 
    datax$i[  datax$m.party == datax$p.party] <- 1
    datax$i[  datax$p.party == 13 & datax$m.party == 15] <- 1}
    
    datax$ivari <- datax$i*datax$vari
    datax$it <- datax$i*datax$t
    datax$itrun <- datax$i*datax$t*datax$run
    datax$irun <- datax$i*datax$run
    
    reg <- ivreg(formul  , weights=wght, data=datax) 
    reg2 <- ivreg(formulx  , weights=wght, data=datax)
    results <- coeftest(reg,  vcov = vcovHC(reg, type="HC3"))[2:3,] ; v <- vcovHC(reg, type="HC3")
    results2 <-coeftest(reg2,  vcov = vcovHC(reg2), type="HC3")[2,] 
    res[1,] <- results[1,1:2] 
    res[2,1] <- results[1,1]  + results[2,1] 
    res[2,2] <- (v[2,2]  + v[3,3]  + 2*v[2,3] )^.5
    res[3,] <- results2[1:2] 
    
    
    res$high <- res$X1+1.96*res$X2 ; res$low <- res$X1-1.96*res$X2
    nam <- c("All observations","Lead of the ticket or Vice","Other status in coalition")
    res$names <- c(3,2,1)
    if(i==1) res$g <- "Gubernatorial"
    if(i==2) res$g <- "Presidential"
    
    if(i==1) {resx <- res}else{resx <- rbind(resx,res)}
  }
  
  nam <- c("All observations","Subsample: \n Lead of the ticket or Vice","Subsample: \n Other status in coalition")
  
  ggplot(resx, aes(x=names, y=X1, ymin=low, ymax=high, group=g, color=g)) + theme_bw() +
    theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
    geom_pointrange(aes(group=g, color=g), position = position_dodge(width = 1/2), shape=16) +
    scale_color_manual(values=c("gray25","gray75"), name="2014 Election") +
    scale_y_continuous(breaks=c(-30,-15,0,15,30)) +
    scale_x_continuous(breaks=c(1,2,3), labels=nam)+
    geom_hline(yintercept=0, linetype=2)+
    #coord_flip() +
    theme(axis.title = element_text(colour="black", size=sz, family="A")) +
    theme(axis.title.x = element_blank()) +
    theme(axis.text = element_text(colour="black", size=sz, family="A")) +
    theme(legend.text = element_text(colour="black", size=sz, family="A")) +
    theme(legend.title = element_text(colour="black", size=sz, family="A")) +
    ylab("Vote percentage")+
    theme(legend.position = c(0.15,0.15))
  
  
  
  
#############################################################################################################################################  
  
  
###### Figure A2: Heterogeneity in electoral losses, by status in higher coalitions   #######################################################
  
  data_aux <- maindata
  data_aux$vari <- (data_aux$seats)
  band <- round(b1[1],2)
  

  formul <- as.formula(paste("var ~  (t + trun + run )* inter   + factor(sta) ",cov1,cov2,sep=""))

  res <- data.frame(matrix(0,3,2)) 
  
  data_aux$s <- data_aux$g.support*data_aux$p.support*data_aux$f.support
  data_aux$var <- data_aux$indx*100 

  datax <- subset(data_aux, abs(run) <= band & s == 1 & f.cand > 1 & cut <= 300  )
  datax <- .Weighting(datax,1,band)
  
  datax$cutto <- 11
  datax$cutto[datax$cut == 30] <- 13
  datax$cutto[datax$cut == 50] <- 15
  datax$cutto[datax$cut == 80] <- 17
  datax$cutto[datax$cut == 120] <- 19
  datax$cutto[datax$cut == 160] <- 21
  datax$cutto[datax$cut == 300] <- 23
  datax$inter <- datax$cutto-2

  reg <- lm(formul  , weights=wght, data=datax) 
  
  rr <- coeftest(reg)
  vv <- vcovHC(reg, type="HC3")
  
  vec <- round(seq(from= -14, to = 21,length.out=6),2)
  vec2 <- c(9,11,13,15,17,19,21)
  .Newplot(data=datax,r=rr,v=vv,xvar="inter",minD=9,maxD=21,bins1=12,bins2=7,shift=14,bb=vec,degree=1,multi=8,oneside=0,
                  x.title="Baseline number of seats",y.title="Marginal RD effect of a 2 seat increase",bb3=vec2) 
  
  
  
############################################################################################################################################# 
  
  
##### Figure A3: Heterogeneity in electoral losses, by partisanship of aligned councilors ###################################################  
  
  
  data_aux <- maindata
  data_aux$vari <- (data_aux$seats)
  band <- round(b1[1],2)
  
  base_for_i <- "var ~  vari + ivari  + i + run + trun + irun + itrun + factor(cut) + factor(sta)"
  iv_i <- "| .-vari -ivari  + t + it"

  res <- data.frame(matrix(0,6,2)) #; names(res) <- c("gov","pres")
  
  for (i in 1:2){
    
    if(i == 1) {data_aux$s <- data_aux$g.support ; data_aux$var <- data_aux$g.pc*100 ; data_aux$share <- data_aux$g.share}
    if(i == 2) {data_aux$s <- data_aux$p.support ; data_aux$var <- data_aux$p.pc*100 ; data_aux$share <- data_aux$p.share}
    if(i == 1) datax <- subset(data_aux, abs(run) <= band & s == 1 & f.cand > 0 & cut <= 300 & mg.team>0 )
    if(i == 2) datax <- subset(data_aux, abs(run) <= band & s == 1 & f.cand > 0 & cut <= 300 & mp.team>0 )
    
    datax <- .Weighting(datax,1,band)

    if(i == 1) formul <- as.formula(paste(base_for_i,cov1,"+ mg.team",cov2,iv_i,sep=""))
    if(i == 2) formul <- as.formula(paste(base_for_i,cov1,"+ mp.team",cov2,iv_i,sep=""))
    
    if(i == 1) datax$j <- datax$m.team.party / datax$mg.team
    if(i == 2) datax$j <- datax$m.team.party / datax$mp.team

    med <- round(median(datax$j[!is.na(datax$j)]),5)
    
    datax$i <- 0 ; datax$i[datax$j >= med] <- 1
    
    datax$ivari <- datax$i*datax$vari
    datax$it <- datax$i*datax$t
    datax$itrun <- datax$i*datax$t*datax$run
    datax$irun <- datax$i*datax$run
    
    
    reg <- ivreg(formul  , weights=wght, data=datax) 
    
    results <- coeftest(reg,  vcov = vcovHC(reg, type="HC3"))[2:3,] ; v <- vcovHC(reg, type="HC3")
    res[i*3-2,] <- results[1,1:2] 
    res[i*3,] <- results[2,1:2] 
    res[i*3-1,1] <- results[1,1]  + results[2,1] 
    res[i*3-1,2] <- (v[2,2]  + v[3,3]  + 2*v[2,3] )^.5
    
  }
  
  res$Coalition <- "Gubernatorial"
  res$Coalition[4:6] <- "Presidential"
  
  res$high <- res$X1+1.96*res$X2 ; res$low <- res$X1-1.96*res$X2
  nam <- c("Sub-sample 1: \n Mayor's aligned partners \n are less partisan","Sub-sample 2: \n Mayor's aligned partners \n are more partisan","Difference")
  res$names <- c(1,2,3,1,2,3)
  
  ggplot(res, aes(x=names, y=X1, ymin=low, ymax=high, group=Coalition)) + theme_bw() +
    theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
    geom_pointrange(aes(color=Coalition, group=Coalition), position = position_dodge(width = 1/2), shape=16) +
    scale_color_manual(values=c("gray25","gray75"),name="2014 Election") +
    scale_y_continuous(breaks=c(-30,-15,0,15,30)) +
    scale_x_continuous(breaks=c(1,2,3), labels=nam)+
    geom_hline(yintercept=0, linetype=2)+
    #coord_flip() +
    theme(axis.title = element_text(colour="black", size=sz, family="A")) +
    theme(axis.title.x = element_blank()) +
    theme(axis.text = element_text(colour="black", size=sz, family="A")) +
    theme(legend.text = element_text(colour="black", size=sz, family="A")) +
    theme(legend.title = element_text(colour="black", size=sz, family="A")) +
    ylab("Vote percentage")+
    theme(legend.position = c(0.5,0.85))
  
  
  
#################################################################################################################################################  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  